import 'dayjs/locale/zh-cn';

import zhCN from 'ant-design-vue/es/locale/zh_CN';
import dayjs from 'dayjs';
import { defineStore } from 'pinia';

import { Settings } from '@/components/settings/type/index';

dayjs.locale('zh-cn');

export const useSettingStore = defineStore('settings', {
  state: (): Settings => {
    return {
      system: {
        title: 'CloudWeb',
        logo: '//yan.zszhyl.com/icon/wasWeb/logo/logo@2x.png',
      },
      theme: {
        color: '#722ED1',
        mode: 'dark',
      },
      navigation: {
        layout: 'side',
        fixedHeader: true,
        fixedSide: true,
      },
      animate: {
        name: 'back',
        directions: 'left',
        disabled: false,
      },
      others: {
        tagViews: true,
        hideSettings: false,
      },
      locale: zhCN,
      size: 'default',
    };
  },
  getters: {
    antTheme: (state) => {
      return {
        token: {
          colorPrimary: state.theme.color,
          colorInfo: state.theme.color,
        },
      };
    },
  },
  actions: {
    /**
     * 改变颜色
     * @param color
     */
    changeColor(color: string) {
      this.theme.color = color;
      // element颜色改变
      const el = document.documentElement;
      getComputedStyle(el).getPropertyValue(`--el-color-primary`);
      el.style.setProperty('--el-color-primary-dark-2', `${this.getDarkColor(color, 0.1)}`);
      el.style.setProperty('--el-color-primary', color);
      // 颜色变浅
      for (let i = 1; i <= 9; i++) {
        el.style.setProperty(`--el-color-primary-light-${i}`, `${this.getLightColor(color, i / 10)}`);
      }
    },
    /**
     * 更改模式
     * @param mode 类型
     */
    changeModel(mode: 'dark' | 'light') {
      this.theme.mode = mode;
    },
    changeSize(size: 'large' | 'default' | 'small') {
      this.size = size;
    },
    getDarkColor(color: string, level: number) {
      const rgb = this.hexToRgb(color);
      for (let i = 0; i < 3; i++) rgb[i] = Math.floor(rgb[i] * (1 - level));
      return this.rgbToHex(rgb[0], rgb[1], rgb[2]);
    },
    rgbToHex(r: any, g: any, b: any) {
      const hexs = [r.toString(16), g.toString(16), b.toString(16)];
      for (let i = 0; i < 3; i++) if (hexs[i].length === 1) hexs[i] = `0${hexs[i]}`;
      return `#${hexs.join('')}`;
    },
    hexToRgb(str: any) {
      let hexs: any = '';
      str = str.replace('#', '');
      hexs = str.match(/../g);
      for (let i = 0; i < 3; i++) hexs[i] = parseInt(hexs[i], 16);
      return hexs;
    },
    getLightColor(color: string, level: number) {
      const rgb = this.hexToRgb(color);
      for (let i = 0; i < 3; i++) rgb[i] = Math.floor((255 - rgb[i]) * level + rgb[i]);
      return this.rgbToHex(rgb[0], rgb[1], rgb[2]);
    },
  },
  persist: true,
});
